package edu.biwu.cookie05;

import edu.biwu.utils.CookieUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/lastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUtils.getCookie(cookies, "lastVisited");

        if (cookie==null) {
            response.getWriter().write("欢迎第一次访问");
        }else{
            String dateStr = cookie.getValue();
            String decode = URLDecoder.decode(dateStr, "utf-8");
            response.getWriter().write("您上次访问的时间："+decode);
        }

        String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        String encodeDate = URLEncoder.encode(format, "UTF-8");

        Cookie lastVisitedCookie = new Cookie("lastVisited",encodeDate);
        lastVisitedCookie.setMaxAge(7*24*60*60);
        lastVisitedCookie.setPath(request.getContextPath());
        response.addCookie(lastVisitedCookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
